package com.hddz.acquisition.activity.grzx;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.jb.barcode.BarcodeManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

import com.hddz.acquisition.AppSetting;
import com.hddz.acquisition.R;
import com.hddz.acquisition.barcode.ScanService;

public class GRSZActivity extends Activity {

    private ScanService scanService;
    private BarcodeManager scanManager;
    private boolean bind = false;
    public AlertDialog loadingBulider;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
        }
    };

    private Runnable closeLodingIcon = new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            closeLoadinDialog();
        }
    };

    public void showLoadinDialog() {
        if (null == loadingBulider) {
            View view = LayoutInflater.from(this).inflate(
                    R.layout.layout_widget_loading, null);
            AlertDialog.Builder builder = new AlertDialog.Builder(
                    new ContextThemeWrapper(this, R.style.myLoadingTheme));
            loadingBulider = builder.create();
            loadingBulider.setCancelable(false);
            loadingBulider.setView(view, 0, 0, 0, 0);
            loadingBulider
                    .setOnKeyListener(new DialogInterface.OnKeyListener() {

                        @Override
                        public boolean onKey(DialogInterface dialog,
                                             int keyCode, KeyEvent event) {
                            // TODO Auto-generated method stub
                            if (keyCode == KeyEvent.KEYCODE_BACK) {
                                closeLoadinDialog();
                            }
                            return false;
                        }
                    });
            loadingBulider.setCanceledOnTouchOutside(false);
        }
        if (!loadingBulider.isShowing()) {
            loadingBulider.show();
        }
    }

    public void closeLoadinDialog() {
        if (!isFinishing()) {
            if (null != loadingBulider) {
                if (loadingBulider.isShowing()) {
                    loadingBulider.dismiss();
                }
            }
        }
    }

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_grzx_grsz);
        // TODO Auto-generated method stub

        ((EditText) findViewById(R.id.tv_server_address))
                .setText(AppSetting.getAppSetting(GRSZActivity.this).SERVER_ADDRESS.get());
        ((EditText) findViewById(R.id.tv_server_address)).addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                AppSetting.getAppSetting(GRSZActivity.this).SERVER_ADDRESS.set(s.toString());
            }
        });

        ((EditText) findViewById(R.id.tv_user_name)).setText(AppSetting.getAppSetting(GRSZActivity.this).UN.get());
        ((EditText) findViewById(R.id.tv_user_name)).addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                AppSetting.getAppSetting(GRSZActivity.this).UN.set(s.toString());
            }
        });

        ((EditText) findViewById(R.id.tv_code_mode)).setText(AppSetting.getAppSetting(GRSZActivity.this).CODE_MODE
                .get());
        ((EditText) findViewById(R.id.tv_code_mode)).addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                String temp = s.toString();
                for (int i = 0; i < temp.length(); i++) {
                    if (Character.isDigit(temp.charAt(i)) || temp.charAt(i) == ',') {
                        continue;
                    } else {
                        return;
                    }
                }

                if (temp.charAt(temp.length() - 1) == ',')
                    return;

                AppSetting.getAppSetting(GRSZActivity.this).CODE_MODE.set(s.toString());

                String[] temps = temp.split(",");
                int[] codemode = new int[temps.length];
                for (int i = 0; i < temps.length; i++) {
                    codemode[i] = Integer.parseInt(temps[i]);
                }
                AppSetting.codeMode = codemode;
            }
        });


        ((EditText) findViewById(R.id.et_vouchtype))
                .setText(AppSetting.getAppSetting(GRSZActivity.this).VOUCH_TYPE.get());
        ((EditText) findViewById(R.id.et_vouchtype)).addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                String temp = s.toString();
                if (temp.length() >= 2) {
                    AppSetting.getAppSetting(GRSZActivity.this).VOUCH_TYPE.set(s.toString());
                }
            }
        });

        ((EditText) findViewById(R.id.et_importtype))
                .setText(AppSetting.getAppSetting(GRSZActivity.this).IMPORT_TYPE.get());
        ((EditText) findViewById(R.id.et_importtype)).addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                String temp = s.toString();
                if (temp.length() >= 2) {
                    AppSetting.getAppSetting(GRSZActivity.this).IMPORT_TYPE.set(s.toString());
                }
            }
        });


        //showLoadinDialog();
        Intent service = new Intent(this, ScanService.class);
        //startService(service);
        bindService(service, serviceConnection, BIND_AUTO_CREATE);
        System.out.println("onCreat()");

    }

    public void onBack(View view) {
        finish();
    }

    public boolean dispatchKeyEvent(KeyEvent event) {
        // TODO Auto-generated method stub
        if (event.getAction() == KeyEvent.ACTION_UP) {
            switch (event.getKeyCode()) {
                case KeyEvent.KEYCODE_F1:
                    findViewById(R.id.ll_code_mode).setVisibility(View.VISIBLE);
                    return true;
                default:
                    break;
            }
        }
        return super.dispatchKeyEvent(event);
    }

    ServiceConnection serviceConnection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            bind = false;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            bind = true;
            ScanService.MyBinder myBinder = (ScanService.MyBinder) service;
            scanService = myBinder.getService();
            // scanManager.setIsScan(false);
            scanManager = scanService.getScanManager();


            ArrayAdapter<String> adpter_model = new ArrayAdapter<String>(GRSZActivity.this,
                    R.layout.spinner_item, getResources().getStringArray(
                    R.array.Scan_model));
            ((Spinner) findViewById(R.id.spinner_type)).setAdapter(adpter_model);
            ((Spinner) findViewById(R.id.spinner_type)).setSelection(scanManager.getScannerModel());
            ((Spinner) findViewById(R.id.spinner_type))
                    .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                        @Override
                        public void onItemSelected(AdapterView<?> arg0, View arg1,
                                                   int arg2, long arg3) {
                            if (scanManager.getScannerModel() != arg2) {
                                scanManager.setScannerModel(arg2);
                                showLoadinDialog();
                                sendBroadcast(new Intent("ReLoadCom"));
                                mHandler.postDelayed(closeLodingIcon, 3000);
                            }
                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> arg0) {
                            // TODO Auto-generated method stub

                        }
                    });

            closeLoadinDialog();
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (scanService != null) {
            if (null != scanManager) {
//				scanManager.Barcode_Stop();
            }
        }

        if (bind) {
            unbindService(serviceConnection);
        }

    }
}
